<?php
    
    getAddrByIP("14.215.177.38");
    
    class OBJ{};		//空对象
    class RST{
        public $error=0;     	          //是否出错
        public $message="OK";	//错误信息或其它
        public $data;			        //结果，为JSON格式
        public $newID=-1;		     //插入新记录的id，用于带有更新数据的请求
    };



    function cout($str){
        return;
        $open = fopen("log.txt", "a+" );
        fwrite($open, $str . "\t" . date("Y-m-d H:i:s", time()) . "\r\n");
        fclose($open);
    }
    
    function out($obj){
        cout(json_encode($obj));
    }

    function GetAddr() {
        $ip = $_SERVER["REMOTE_ADDR"];
        $ip = "61.139.2.69";
        if(isOutIP($ip)){
            cout("outip");
            return getAddrByIP($ip);
        }
        return array("ip" => $ip) ;
    }
    
    
    //百度接口参数计算
    function caculateAKSN($ak, $sk, $url, $querystring_arrays, $method = 'GET')
    {
        if ($method === 'POST') ksort($querystring_arrays);
        $querystring = http_build_query($querystring_arrays);
        return md5(urlencode($url.'?'.$querystring.$sk));
    }
    
    //百度ip接口调用准备，ak, sn参数生成
    function getBaiduIpUrl($ip=""){
        $url = "http://api.map.baidu.com/location/ip?ip=%s&output=json&ak=%s&sn=%s";
        $ak = 'hOwhByDNiZZ0XqkNQFZGcRa2';
        $sk = 'XwlG0vbOzRq12kpNyo1uPNG1gk5Eq0Ni';
        $uri = '/location/ip';
        
        if($ip=="")$ip = @$_SERVER["REMOTE_ADDR"];
        
        $querystring_arrays = array (
            'ip' => $ip,
            'output' => "json",
            'ak' => $ak
        );
        
        $sn = caculateAKSN($ak, $sk, $uri, $querystring_arrays);
        $target = sprintf($url, urlencode($ip), $ak, $sn);
        
        return $target;
    }
    
    //获取地理位置所有信息，返回数组对应3字段
    function getAddrByIP($ip){
        // ip, city, addr, addrDetail
        $data = array($ip, "", "", "");
        $url = getBaiduIpUrl($ip);
        $res = file_get_contents($url);
        if(empty($res))return $data; 
        
        $obj = json_decode($res);
        $temp = explode('|', $obj->address);
        $data[1] = count($temp)>2 ? $temp[2] : "";  //city
        $data[2] = $obj->address;                   //addr
        $data[3] = $res;                            //addrDetail

        return $data;
    }
    
    
    function isOutIP($ip)
    {
        if(count(explode('.', $ip))!=4)return false;
        if(in_array(strtok($ip, '.'), array('10', '127', '168', '192')))return false;
        return true;
    }
    
    
?>